from PySide6.QtCore import QDateTime, QTime
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QTableWidgetItem, \
    QHeaderView

from file_py.SqlHelper import SqlHelper
from ui.query_ui import Ui_Form


class QueryData(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        # 获取当前日期时间
        current_date_time = QDateTime.currentDateTime()
        # 设置日期为今天，同时将小时、分钟和秒设置为0
        current_date_time.setDate(current_date_time.date())
        current_date_time.setTime(QTime(0, 0, 0))
        self.ui.Sdate.setDateTime(current_date_time)
        current_date_time.setTime(QTime(23, 59, 59))
        self.ui.Edate.setDateTime(current_date_time)
        self.ui.btn_query.clicked.connect(self.query_data)
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.sqlHelper = SqlHelper()

    def query_data(self):
        start_date = self.ui.Sdate.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        end_date = self.ui.Edate.dateTime().toString("yyyy-MM-dd hh:mm:ss")
        sql = f"select cpn,ipn,operTime from Operation where operTime>='{start_date}' AND operTime<='{end_date}'"
        data = self.sqlHelper.Query_SQLServer_by_SQL(sql)
        self.ui.tableWidget.setRowCount(len(data))
        for i, row in enumerate(data.values):
            for j, value in enumerate(row):
                self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(value)))
